<template>
    <div style="position: relative;">
        <div class="w-form-header">
            <!-- <span>
                <span style="margin-right: 8px">大办单详情</span
                ><span style="font-size: 16px;font-weight: 500;">{{ formData.status }}</span>
                <el-tag style="font-size: 16px; font-weight: 500; margin-left: 16px;">{{ formData.printStatus }}</el-tag>
            </span> -->
            <div v-if="!isViewOp">
                <el-button type="primary" @click="preview">打印预览</el-button>
                <template v-if="userStore.userInfo.authority?.authorityId !== 1000">
                    <el-button v-if="exportDocumentBtn" type="primary"  v-auth="btnAuth['导出备料清单']"
                        @click="largeScaleOrderExportMaterialListFun()">导出备料清单</el-button>
                    <el-button v-if="sapBtn" type="primary" @click="toSapFun()" v-auth="btnAuth['汇入sap']">汇入SAP</el-button>
                    <!-- <el-button type="primary" v-if="leiyinBtn" @click="print()">列印</el-button> -->
                    <!-- <el-button v-if="saveBtn" type="success" @click="confirmNoReasonForm()"
                        >保存草稿</el-button
                    > -->
                    <el-button v-if="editBtn" type="success" @click="submitupdateForm('修改')">{{ formData.status === '草稿' ? '编辑' :
                        '修改' }}</el-button>
                    <el-button v-if="stopBtn" type="warning" @click="updateStatus('暫停', true)">暫停</el-button>
                    <el-button v-if="cancelBtn" type="danger" @click="updateStatus('終止', true)">終止</el-button>
                    <el-button v-if="rebackBtn" v-auth="btnAuth.rebackBtn" type="danger" @click="updateStatus('退回', true)">退回</el-button>
                    <el-button v-if="recoverBtn" type="danger" @click="updateStatus('恢復', true)">恢復</el-button>
                    <el-button v-if="completeBtn" v-auth="btnAuth.completeBtn" type="success" @click="updateStatus('完成', true)">完成</el-button>
                    <!-- <el-button v-if="checkSuccessBtn" type="success">审核通过</el-button> -->
                    <!-- <el-button v-if="equipmentPrintBtn" type="primary">已列印</el-button> -->
                    <el-button v-if="submitHandleBtn1" type="success" @click="updateStatus('提交', true)">提交</el-button>
                    <el-button v-if="submitHandleBtn" v-auth="btnAuth.submitHandleBtn" type="success" @click="updateStatus('提交', true)">提交</el-button>
                    <el-button v-if="agreeUpdateBtn"  v-auth="btnAuth.agreeBtn" type="success" @click="updateStatus('同意', true)">同意</el-button>
                    <el-button v-if="refuseUpdateBtn" v-auth="btnAuth.refuseBtn" type="danger" @click="updateStatus('拒絕', true)">拒絕</el-button>
                    <el-button v-if="customerSubmitBtn" :disabled="formData.verifyTime" type="danger"
                        @click="confirmOrder">客户确认</el-button>

                        <el-button  type="danger" @click="editBDQX" v-auth="btnAuth['修改办单去向']">修改办单去向</el-button>
                    <span v-if="sapBtn" v-auth="btnAuth.sapParam">
                        <el-select v-model="sapParam.steps" placeholder="请选择" style="width: 120px;margin-left:10px">
                            <el-option v-for="item in sapParam.stepList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <!-- <el-select v-if="formData.cumstomerNum == 'ST101' ||
                        formData.customerBrand == 'LEVIS' ||
                        formData.customerBrand == 'levis' ||
                        formData.customerBrand == 'fila' ||
                        formData.customerBrand == 'FILA'
                        " v-model="sapParam.factoryCode" placeholder="请选择" style="width: 80px;margin-left:10px">
                        <el-option :label="'1000'" :value="'1000'" />
                        <el-option :label="'9000'" :value="'9000'" />
                    </el-select> -->
                        <el-button @click="getParams" style="margin-left:10px">下载参数</el-button>
                    </span>
                </template>
                
            </div>
            <div class="title-box" style="margin-left: auto;">
                <span class="version">
                    版本: {{ formData.version || "暂无" }}</span>
                <span v-if="!isViewOp" class="status">{{
                    formData.status
                }}</span>

                <span v-if="!isViewOp" style="font-size: 16px;color: #999;margin-left: 20px">{{
                    formData.printStatus
                }}</span>

                <div style="position: absolute;bottom: -38px;right: 20px;font-size: 16px;white-space: nowrap;z-index: 100;">
                    辦單付數:{{ formData.orderAmountSum }}
                </div>
            </div>
        </div>
        <div class="gva-form-box admin-content">
            <div class="w-form-box">
                <div class="list-header">基本信息</div>
            </div>
            <detailForm :columns="detailFormColumns" :data="formData" separator=":">
                <template #jijiaDemandDate>
                    <el-date-picker v-model="formData.jijiaDemandDate" type="date" disabled
                        value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="选择日期" :clearable="true"></el-date-picker>
                </template>
                <template #orderProcessType>
                    <el-select disabled v-model="formData.orderProcessType" :clearable="true">
                        <el-option v-for="item in dict?.orderType" :key="item.ID" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </template>
                <template #customerDemandDate>
                    <el-date-picker disabled v-model="formData.customerDemandDate" type="date"
                        value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="选择日期" :clearable="true"></el-date-picker>
                </template>
                <template #orderAmount>
                    <el-input-number disabled v-model="formData.orderAmount" placeholder="手动填写" :clearable="true"
                        :controls="false" style="width: 100%" />
                </template>
                <template #isCycleCountIn>
                    <el-radio-group disabled v-model="formData.isCycleCountIn">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </template>
                <template #transferOrder>
                    <el-select disabled v-model="formData.transferOrder" :clearable="true">
                        <el-option v-for="item in dict?.transferOrder" :key="item.ID" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </template>
                <template #piOrderNum>
                    <el-input disabled v-model="formData.piOrderNum" placeholder="手动填写" :clearable="true" />
                </template>
                <template #isNewStyle>
                    <el-radio-group disabled v-model="formData.isNewStyle">
                        <el-radio label="是">是</el-radio>
                        <el-radio label="否">否</el-radio>
                    </el-radio-group>
                </template>
                <template #piDemandDate>
                    <el-date-picker disabled v-model="formData.piDemandDate" type="date" value-format="YYYY-MM-DDTHH:mm:ssZ"
                        placeholder="选择日期" :clearable="true"></el-date-picker>
                </template>
                <template #requireLetterpressMaterial>
                    <el-radio-group disabled v-model="formData.requireLetterpressMaterial">
                        <el-radio label="需要">需要</el-radio>
                        <el-radio label="不需要">不需要</el-radio>
                    </el-radio-group>
                </template>
                <template #isForSpecasavers>
                    <el-radio-group disabled v-model="formData.isForSpecasavers">
                        <el-radio label="是">是</el-radio>
                        <el-radio label="否">否</el-radio>
                    </el-radio-group>
                </template>
                <template #firstOrderReceipt>
                    <el-radio-group disabled v-model="formData.firstOrderReceipt">
                        <el-radio label="有">有</el-radio>
                        <el-radio label="无">无</el-radio>
                    </el-radio-group>
                </template>
                <template #firstOrderReceiptNote>
                    <el-select disabled v-model="formData.firstOrderReceiptNote" :clearable="true">
                        <el-option v-for="item in dict?.firstOrderReceiptNote" :key="item.ID" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </template>
                <template #createUser>
                    <span v-if="formData.createdUser && formData.createdUser.nickName">
                        {{ formData.createdUser.nickName }}
                    </span>
                    <span v-else>{{ formData.createUser }}</span>
                </template>
                <template #updateUser>
                    <span v-if="formData.updatedUser && formData.updatedUser.nickName">
                        {{ formData.updatedUser.nickName }}
                    </span>
                    <span v-else>{{ formData.updateUser }}</span>
                </template>
                <template #FirstCreatedAt>
         
         <span > {{formatDate(formData.FirstCreatedAt )=="1-01-01" ? '' : formatDate(formData.FirstCreatedAt ) }}</span>
       </template>
            </detailForm>
            <el-row style="margin-top: 20px" :gutter="20" class="large-order-form">
                <el-col :span="24">
                    <el-form-item label="办单去向:">
                        <template v-if="formData.cumstomerNum != 'ST101'">
                            <span v-for="(item, index) in dict?.firstOrderDestNoST101" style="margin-right: 12px">{{
                                item.label
                            }}<el-input-number disabled :min="0" :controls="false"
                                    v-model="formData.orderTo[item.label]"
                                    style="margin-left: 8px;width: 33px;" />&ensp;付</span>
                        </template>
                        <template v-else>
                            <span v-for="(item, index) in dict?.firstOrderDestST101" style="margin-right: 12px">{{
                                item.label
                            }}<el-input-number disabled :min="0" :controls="false"
                                    v-model="formData.orderTo[item.label]"
                                    style="margin-left: 8px;width: 33px;" />&ensp;付</span>
                        </template>

                    </el-form-item>
                </el-col>
                <el-col :span="16" v-if="formData.orderTo['其他'] && formData.orderTo['其他'] > 0">
                    <el-form-item :label="`其他原因:`">
                        <el-input v-model="formData.orderTo['otherReason']" disabled type="textarea" :rows="5"
                            placeholder="" :clearable="true" />
                    </el-form-item>
                </el-col>


                <el-col :span="24">
                    <el-form-item :label="`制作部門:`">
                        <el-select :disabled="isViewOp||!btnAuth['制作部门']" v-model="formData.productionDepartment"
                            @change="productionDepartmentChange"   :clearable="false">
                            <el-option v-for="item in dict?.productionDepartment" :key="item.ID" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="`款式备注:`" prop="productStyleNote" >
                        <el-input v-model="formData.productStyleNote" disabled type="textarea" :autosize="{ minRows: 1 }"
                            :maxlength="500" show-word-limit placeholder="" :clearable="true" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="`大办单备注:`" prop="largeScaleNote">
                        <el-input v-model="formData.largeScaleNote" disabled type="textarea" :autosize="{ minRows: 1 }"
                            :maxlength="500" show-word-limit placeholder="" :clearable="true" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="`刻字模备注:`" prop="engraveMoldNote">
                        <el-input v-model="formData.engraveMoldNote" disabled type="textarea" :autosize="{ minRows: 1 }"
                            :maxlength="500" show-word-limit placeholder="" :clearable="true" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="`附办说明:`" prop="orderExplain">
                        <el-input v-model="formData.orderExplain" disabled type="textarea" :autosize="{ minRows: 1 }"
                            :maxlength="500" show-word-limit placeholder="" :clearable="true" />
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                    <el-form-item :label="`修改备注:`" prop="modifyNote">
                        <el-input v-model="formData.modifyNote" disabled type="textarea" :autosize="{ minRows: 1 }"
                            :maxlength="500" show-word-limit placeholder="" :clearable="true" />
                    </el-form-item>
                </el-col> -->
            </el-row>
            <div class="w-form-box">
                <div class="list-header">办房复期</div>
            </div>
            <LTable :columns="boardMakingColumns" :tableData="boardMakingTalbeData" :pagination="false" :selection="false"
                :showConfig="false" :tableProps="{}">
                <template #action>
                    <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
                        <el-button type="primary" icon="plus" :disabled="isViewOp" @click="addBoardMaking">添加</el-button>
                    </div>
                </template>
                <template #event>
                    <el-table-column align="left" label="操作" fixed="right" min-width="260">
                        <template #default="{ row }">
                            <el-button v-if="row.status === '审核中'" type="primary" link class="table-button"
                                @click="auditBoardMaking(row)">
                                <el-icon style="margin-right: 5px">
                                    <InfoFilled />
                                </el-icon>
                                审核
                            </el-button>
                        </template>
                    </el-table-column>
                </template>
                <template #status="{ row }">
                    <span v-if="row.status === '审核中'">审核中</span>
                    <span v-if="row.status === '通过'" style="color: #67c23a">通过</span>
                    <span v-if="row.status === '拒绝'" style="color: #f56c6c">拒绝</span>
                </template>
            </LTable>
            <div class="w-form-box">
                <div class="list-header">尺码</div>
            </div>
            <LTable v-if="sizeTableData.length <= 0" :columns="sizeColumns" :tableData="sizeTableData" :pagination="false"
                :selection="false" :showConfig="false" :tableProps="{}"></LTable>
            <LTable v-else :columns="sizeColumns" :tableData="sizeTableData" :pagination="false" :selection="false"
                :showConfig="false" :tableProps="{
                    showSummary: true,
                    summaryMethod: getSumaryMethod
                }">
                <template #color="{ row, column }">
                    <el-input v-model="row.colorNum[column.prop]" disabled
                        @input="validNumber(row.colorNum, column.prop)" />
                </template>
                <template #luckTilt="{ row }">
                    <span><el-input-number :controls="false" disabled style="width: 60px; height: 28px" :max="255" :min="0"
                            v-model="row.luckTilt" /></span>
                </template>
                <template #drawingList="{ row }">
                    <!-- <el-select v-model="row.drawingList" disabled :clearable="true">
                        <el-option
                            v-for="item in ddmsSpecDrawingListListData"
                            :key="item.fileUrl"
                            :label="item.drawingName"
                            :value="item.fileUrl"
                        />
                    </el-select> -->
                    <span v-if="row.drawingName">{{ row.drawingName }}&emsp;<a href="javascript:void(0)"
                            @click="downloadFile(row)">下载</a></span>
                </template>
            </LTable>
            <div class="w-form-box">
                <div class="list-header">做色要求</div>
            </div>
            <LTable :columns="colorColumns" :tableData="colorTableData" :pagination="false" :selection="false"
                :showConfig="false" :tableProps="{}">
            </LTable>
            <div >
                <div class="w-form-box">
                    <div class="list-header">与上版本配件对比</div>
                </div>
                <!-- <div class="version-PK">
                    <el-descriptions title="" :column="1" border>
                        <el-descriptions-item label="新增配件"
                            label-align="center">{{ addAccessory.join(',') }}</el-descriptions-item>
                        <el-descriptions-item label="删除配件" label-class-name="delete-acc"
                            label-align="center">{{ deleteAccessory.join(',') }}</el-descriptions-item>
                    </el-descriptions>
                </div> -->
                <div>
                    <el-table
                        :data="[{
                            addAccessory:addAccessory,
                            deleteAccessory:deleteAccessory,
                            modifyNote:formData.modifyNote
                        }]"
                        border
                        style="width: 100%"
                        class="table-style-1"
                    >
                        <el-table-column
                            label="新增配件"
                            prop="addAccessory"
                            :min-width="'20%'"
                        >
                            <template #default="{ row }">
                            <div v-for="item in addAccessory">{{item}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="删除配件"
                            prop="deleteAccessory"
                            :min-width="'20%'"
                        >
                            <template #default="{ row }">
                            <div v-for="item in deleteAccessory">{{item}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="修改备注"
                            prop="modifyNote"
                            :min-width="'60%'"
                        >
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="w-form-box">
                <div class="list-header">配件规格清单</div>
            </div>
            <LTable :columns="partColumns" :tableData="partTableData" :pagination="false" :selection="false"
                :showConfig="false" :tableProps="{
                    defaultExpandAll: true,
                    rowKey: 'ID',
                    treeProps: {
                        children: 'children',
                        hasChildren: 'hasChildren',
                    },
                }">
            </LTable>
            <div class="w-form-box">
                <div class="list-header">标志\图案工艺说明</div>
            </div>
            <LTable :columns="signColumns" :tableData="signTableData" :pagination="false" :selection="false"
                :showConfig="false" :tableProps="{}">
            </LTable>
            <div class="w-form-box">
                <div class="list-header">测试标准</div>
            </div>
            <LTable :columns="testStandardColumns" :tableData="testStandardDocumentListData" :pagination="false"
                :selection="false" :showConfig="false" :tableProps="{}">
            </LTable>
            <!-- <div class="w-form-box">
                <div class="list-header">历史修改备注</div>
            </div>
            <LTable :columns="historyNoteColumns" :tableData="historyNoteTableData" :pagination="false" :selection="false"
                :showConfig="false" :tableProps="{}">
            </LTable> -->
            <div class="w-form-box">
                <div class="list-header">操作修改记录</div>
               
            </div>
            <el-table :data="historyNoteTableData" border style="width: 100%" >
              <el-table-column prop="date" label="操作人" width="80"  >
                <template #default="scope" >
                 <div style="width: 10px;height: 5px;"@dblclick="showhistoryNoteTableData(scope.row)"></div>   {{ scope.row.operator== "" ? scope.row.createUser : scope.row.operator== "" ? scope.row.updateUser : scope.row.operator}}
                </template>
              </el-table-column>
              
              <el-table-column prop="UpdatedAt" label="操作时间" width="140"  >
                <template #default="scope">{{ formatDateS(scope.row.UpdatedAt)}}</template>
              </el-table-column>
              <el-table-column prop="action" label="操作" />
              <el-table-column prop="dataBefore" label="操作前" />
              <el-table-column prop="dataAfter" label="操作後" />
              <!-- <el-table-column prop="content" label="更改内容" /> -->
              <!-- <el-table-column prop="reason" label="更改原因" /> -->
              <!-- <el-table-column prop="detail" label="详细说明" /> -->
              <el-table-column prop="" label="版本" width="60" >
                <template #default="scope">{{ scope.row.version}}</template>
              </el-table-column>
            </el-table>
            <el-dialog v-model="historyNoteTableDatadialog" title="" width="800">
                <pre>{{ historyNoteTableDatas }}</pre>
            </el-dialog>
        </div>

        <!-- 添加备注 -->
        <el-dialog v-model="addNoteDialogFormVisible" destroy-on-close width="50%" title="添加修改备注">
            <el-form ref="addNoteFormRef" style="display: flex" inline :model="addNoteForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="内容分类：">
                            <el-checkbox-group v-model="addNoteForm.content">
                                <el-checkbox v-for="item in contentCate" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="原因分类：">
                            <el-checkbox-group v-model="addNoteForm.reason">
                                <el-checkbox v-for="item in reasonCate" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="详细说明：" style="width: 100%">
                            <textarea v-model="addNoteForm.detail" :rows="5" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">

                    <el-button type="primary" @click="confirmEditForm('修改')">确定</el-button>
                    <el-button @click="
                        (addNoteForm = {}),
                        (addNoteDialogFormVisible = false)
                        ">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加办房复期 -->
        <el-dialog v-if="boardMakingVisible" v-model="boardMakingVisible" destroy-on-close width="50%" title="办房复期">
            <el-form ref="boardMakingFormRef" :model="boardMakingForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="复期日期：">
                            <el-date-picker v-model="boardMakingForm.deliveryDate" type="date"
                                value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="选择日期" :clearable="true"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="详细说明：" style="width: 100%">
                            <textarea v-model="boardMakingForm.detailDescription" :rows="5" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">

                    <el-button type="primary" @click="addBoardMakingSubmit">确定</el-button>
                    <el-button @click="
                        (boardMakingForm = {}), (boardMakingVisible = false)
                        ">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 审核办房复期 -->
        <el-dialog v-if="auditBoardMakingVisible" v-model="auditBoardMakingVisible" destroy-on-close width="50%"
            title="办房复期">
            <el-form ref="auditBoardMakingFormRef" :model="auditBoardMakingForm">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="复期日期：">
                            <el-radio-group v-model="auditBoardMakingForm.status">
                                <el-radio value="通过" size="large" border style="color: #67c23a">通过</el-radio>
                                <el-radio value="拒绝" size="large" border style="color: #f56c6c">拒绝</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="详细说明：" style="width: 100%">
                            <textarea v-model="auditBoardMakingForm.auditDescription" :rows="5" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">

                    <el-button type="primary" @click="auditBoardMakingSubmit">确定</el-button>
                    <el-button @click="
                        (auditBoardMakingForm = {}),
                        (auditBoardMakingVisible = false)
                        ">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 客户确认大办单 -->
        <el-dialog v-if="confirmOrderVisible" v-model="confirmOrderVisible" destroy-on-close width="50%" title="客户确认大办单">
            <el-form ref="confirmOrderFormRef" :model="confirmOrderForm" :rules="confirmOrderFormRules">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="客户确认日期：" prop="verifyTime">
                            <el-date-picker v-model="confirmOrderForm.verifyTime" type="date"
                                value-format="YYYY-MM-DDTHH:mm:ssZ" placeholder="选择日期" :clearable="true"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">

                    <el-button type="primary" @click="handleConfirmOrder">确定</el-button>
                    <el-button @click="
                        (confirmOrderForm = {}),
                        (confirmOrderVisible = false)
                        ">取消</el-button>
                </div>
            </template>
        </el-dialog>

         <!-- 修改办单去向弹窗 -->
        <el-dialog v-if="editBDQXdialog" v-model="editBDQXdialog" destroy-on-close width="50%" title="修改办单去向">
            <el-form-item label="办单去向:">
                        <template v-if="formData.cumstomerNum != 'ST101'">
                            <span v-for="(item, index) in dict?.firstOrderDestNoST101" style="margin-right: 12px;margin-bottom: 8px;">{{
                                item.label
                            }}<el-input-number  :min="0" :controls="false"
                                    @change="BDQXchange"
                                    v-model="formData.orderTo[item.label]"
                                    :disabled="item.label == '其他'"
                                    style="margin-left: 8px;width: 33px;" />&ensp;付</span>
                        </template>
                        <template v-else>
                            <span v-for="(item, index) in dict?.firstOrderDestST101" style="margin-right: 12px;margin-bottom: 8px;">{{
                                item.label
                            }}<el-input-number  :min="0" :controls="false"
                                    @change="BDQXchange"
                                    :disabled="item.label == '其他'"
                                    v-model="formData.orderTo[item.label]"
                                    style="margin-left: 8px;width: 33px;" />&ensp;付</span>
                        </template>

                    </el-form-item>
                    <el-form-item :label="`其他原因:`" v-if="formData.orderTo['其他']>0">
                        <el-input v-model="formData.orderTo['otherReason']"  type="textarea" :rows="5"
                            placeholder="" :clearable="true" />
                    </el-form-item>
                    <template #footer>
                        <div class="dialog-footer">

                            <el-button type="primary" @click="handleConfirmBDQX">确定</el-button>
                            <el-button @click="
                                (formData.orderTo = oldeditBDQXData),
                                (editBDQXdialog = false)
                                ">取消</el-button>
                        </div>
                    </template>
        </el-dialog>
        <!-- 汇入sap -->
        <toSap ref="toSapRef" :formData="formData" :type="'largeScaleOrder'" :ID="formData" />
        <previewBox :bianhao="formData.largeScaleNum" v-if="previewDialogShow" @closePreview="closePreview"   :printStyle="getPrintStyle()"   previewType="plmLargeOrderProcessingEdit" @print="print"    @editPrintStatus="editPrintStatus">
            <div>
                <div class="one-box">
                    <div class="ftsz10px">

                    </div>
                    <div style="text-align: center; position: relative; top: -14px;font-weight: bold;">
                        大辦單编號： {{ formData.largeScaleNum }}
                    </div>
                    <div class="ftsz10px" style="margin-right: 10px;font-weight: bold;position: relative;">
                        <div style="position: absolute;bottom: 10px;right: 0;">
                            版本:{{ formData.version || "暂无" }}
                        </div>
                        <div style="position: absolute;bottom: -24px;right: 0;">
                            辦單付數:{{ formData.orderAmountSum }}
                        </div>
                    </div>
                </div>

                <div class="content-box">
                    <div class="title">基本資料</div>
                    <div class="content">

                        <div class="descriptions">
                            <template v-for="(item, key) in detailFormColumns" :key="key">
                                <div class="descriptionsItem" v-if="item.label!='办单付数汇总'">
                                    <span>{{ item.label }}：</span><span>{{item.needformatter ? formatDate(formData[item.prop]) : formData[item.prop]
                                    }}</span>
                                </div>
                            </template>
                            <div class="addLine" >
                                <span>設計規格圖：</span><span>{{ sizeTableData.map(item=>item.drawingName).join(',')||'' }}</span>
                            </div>
                            <div class="addLine">
                                <span>款式備注：</span><span>{{ formData.productStyleNote }}</span>
                            </div>
                            <div class="addLine">
                                <span>大辦單備注：</span><span>{{ formData.largeScaleNote }}</span>
                            </div>
                            <div class="addLine">
                                <span>刻字模備注：</span><span>{{ formData.engraveMoldNote }}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="content-box table4" v-if="formData.modifyNote">
                    <div class="title">与上版本配件对比</div>
                    <div class="content" style=" border-bottom: 0">
                        <div class="myTable-head">
                        <div>新增配件</div>
                        <div>刪除配件</div>
                        <div>修改備注</div>
                        </div>
                        <div
                        class="myTable-content"
                        v-for="(item, index) in [{
                            addAccessory:addAccessory,
                            deleteAccessory:deleteAccessory,
                            modifyNote:formData.modifyNote
                        }]"
                        :key="index"
                        >
                        <div>
                            <div v-for="item in addAccessory">{{item}}</div>
                        </div>
                        <div>
                            <div v-for="item in deleteAccessory">{{item}}</div>
                        </div>
                        <div>
                            {{ item.modifyNote }}
                        </div>
                        
                        </div>
                    </div>
                </div>

                <div class="content-box table1" v-if="colorTableData.length">
                    <div class="title">做色要求</div>
                    <div class="content" style=" border-bottom: 0">
                        <div class="myTable-head">
                            <div></div>
                            <div>客色號</div>
                            <div>客款號</div>
                            <div>本廠颜色描述</div>
                            <div>圈颜色要求</div>
                            <div>脾颜色耍求</div>
                            <div>其它颜色要求</div>
                        </div>
                        <div class="myTable-content" v-for="(item, index) in colorTableData" :key="index">
                            <div>
                                {{ item.colorNum }}
                            </div>
                            <div>
                                {{ item.customerColorNum }}
                            </div>
                            <div>
                                {{ item.customerStyleNum }}
                            </div>
                            <div>
                                {{item.localStyleDesc}}
                            </div>
                            <div>
                                {{ item.circleColorRequire }}
                            </div>
                            <div>
                                {{ item.spleenColorRequire }}
                            </div>
                            <div>
                                {{ item.otherColorRequire }}
                            </div>
                        </div>
                    </div>
                </div>

               

                <div class="content-box table2" v-if="printPartTableData.length">
                    <div class="title">配件及物料清單</div>
                    <div class="content" style=" border-bottom: 0">
                        <div class="myTable-head">
                            <div>斋架/配件</div>
                            <div>自制/外购</div>
                            <div>配件编号</div>
                            <div>物料说明</div>
                            <div>外观规格</div>
                            <div>数量</div>
                            <div>单位</div>
                            <div>备注</div>
                        </div>
                        <div class="myTable-content" v-for="(item, index) in printPartTableData" :key="index">
                            <div>
                                <span :style="{
                                    marginLeft:
                                        item.selfLevel == 1
                                            ? 0
                                            : item.selfLevel == 2
                                                ? '14px'
                                                : '28px',
                                }">
                                    {{ item.accessoryName }}</span>
                            </div>
                            <div>
                                {{ item.orderType || "" }}
                            </div>
                            <div>
                                {{ item.componentNum+item.colorNum || "" }}
                            </div>
                            <div>
                                {{ item.sapDesc || "" }}
                            </div>
                            <div>
                                {{ item.appearanceSpec || "" }}
                            </div>
                            <div>
                                {{ item.num || "" }}
                            </div>
                            <div>
                                {{ item.unit || "" }}
                            </div>
                            <div>
                                {{ item.note || "" }}
                            </div>
                        </div>
                    </div>
                </div>


                <div class="content-box table3" v-if="signTableData.length">
                    <div class="title">標志/工藝圖案説明</div>
                    <div class="content" style="padding-bottom: 20px; border-bottom: 0">
                        <div class="myTable-head">
                            <div>配件名稱</div>
                            <div>位置</div>
                            <div>工藝</div>
                            <div>工藝做色</div>
                            <div>新舊</div>
                            <div>標志/圖案編號</div>
                            <div>尺碼</div>
                            <div>顔色</div>
                        </div>
                        <div class="myTable-content" v-for="(item, index) in signTableData" :key="index">
                            <div>
                                {{ item.accessoryName }}
                            </div>
                            <div>
                                {{ item.position }}
                            </div>
                            <div>
                                {{ item.workmanship }}
                            </div>
                            <div>
                                {{ item.workmanshipColor }}
                            </div>
                            <div>
                                {{ item.workmanshipType }}
                            </div>
                            <div>
                                {{ item.signNum }}
                            </div>
                            <div>
                                {{ item.size }}
                            </div>
                            <div>
                                {{ item.color }}
                            </div>
                        </div>
                    </div>
                </div>


                <div class="content-box table4" v-if="testStandardDocumentListData.length">
                    <div class="title">測試標準</div>
                    <div class="content" style="border-bottom: 0">
                        <div class="myTable-head">
                            <div>測試項目</div>
                            <div>是否出測試報告</div>
                        </div>
                        <div class="myTable-content" v-for="(item, index) in testStandardDocumentListData" :key="index">
                            <div>
                                {{ item.testName }}
                            </div>
                            <div>
                                {{ item.isReport == 'true' ? '是' : '否' }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </previewBox>
    </div>
</template>

<script setup>
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();
import {
    findLargeScaleOrder,
    updateLargeScaleOrder,
    largeScaleOrderMoldHouseList,
    createLargeScaleOrderMoldHouse,
    updateLargeScaleOrderMoldHouse,
    updateLargeScaleOrderStatus,
    largeScaleOrderPrint,
    largeScaleOrderExportMaterialList,
    versionComparison,
    customerConfirmLargeScaleOrderTime,
    updateProductionDepartment,
    moldHousePrint,
    updateLargeScaleOrderTo
} from "@/api/plmLargeScaleOrder";
import { getDdmsSpecDrawingListList } from "@/api/ddmsSpecDrawingList";
import { exportToSap2 } from "@/api/plmProductStyles";
import { deepClone2 } from "@/utils/tool.js";
import { downloadFilePost } from "@/api/comment.js";
import detailForm from "../plmFirstOrderProcessing/components/detailForm/index.vue";
import LTable from "@/components/LTable/LTable.vue";
import toSap from "@/view/plmMasterBOM/toSap.vue";
import { formatDate ,formatDateS} from "@/utils/format";
import { useI18n } from "vue-i18n";
import { emitter } from '@/utils/bus.js'
import { initAccessorySpecs } from '../plmFirstOrderProcessing/ptm_common'
import previewBox from "@/components/preview/preview.vue";
import { useUserStore } from "@/pinia/modules/user";
const { t: il8n } = useI18n();
defineOptions({
    name: "FirstOrderProcessingEdit",
});

// 自动获取字典
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, unref, reactive, onMounted, watchEffect } from "vue";
import { useDict } from "@/utils/dictionary";
import { findProductSpec } from "@/api/plmProductSpec";
const dict = ref({});
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const addNoteDialogFormVisible = ref(false);

const type = ref("");

const detailFormColumns = ref([]);

const formData = ref({
    firstOrderNum: "",
    customerDemandDate: new Date(),
    cumstomerNum: "",
    customerStyleNum: "",
    updateUser: "",
    updateTime: new Date(),
    orderTo: {},
});

const changeAddNoteDialogFormVisible = (bool) => {
    addNoteDialogFormVisible.value = bool;
};

const sizeColumns = ref([]);
const sizeTableData = ref([]);

const colorColumns = ref([]);
const colorTableData = ref([]);

const ddmsSpecDrawingListListData = ref([]);

const addNoteForm = ref({
    content: null,
    reason: null,
});
const addNoteFormRef = ref();
const contentCate = ref([]);
const reasonCate = ref([]);

const boardMakingForm = ref({});
const boardMakingFormRef = ref();

const boardMakingVisible = ref(false);
const changeBoardMakingVisible = (bool) => {
    boardMakingVisible.value = bool;
};

const auditBoardMakingForm = ref({});
const auditBoardMakingFormRef = ref();

const auditBoardMakingVisible = ref(false);
const changeAuditBoardMakingVisible = (bool) => {
    auditBoardMakingVisible.value = bool;
};

const partColumns = ref([
    {
        prop: "accessoryName",
        label: "斋架/配件",
        fixedWidth: 200,
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "orderType",

        label: "自制/外购",
        fixedWidth: 80,
        show: true, // 通过 show 来控制列的展示或隐藏
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "componentNum",
        label: "配件编号",
        show: true,
        tableColumnProps: {
            sortable: false,
            formatter: row => (row.componentNum ? String(row.componentNum) : '') + (row.colorNum ? String(row.colorNum) : '')
        },
    },
    {
        prop: "sapDesc",
        label: "物料说明",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "appearanceSpec",
        label: "外观规格",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "num",
        label: "数量",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "unit",
        label: "单位",
        fixedWidth: 100,
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    // {
    //     prop: "accessoryGroup",
    //     label: "群组",
    //     fixedWidth: 100,
    //     show: true,
    //     tableColumnProps: {
    //         sortable: false,
    //     },
    // },
    {
        prop: "note",
        label: "备注",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
]);
const partTableData = ref([]);

const testStandardColumns = ref([]);
const testStandardDocumentListData = ref([]);

const signColumns = ref([]);
const signTableData = ref([]);

const historyNoteColumns = ref([]);
const historyNoteTableData = ref([]);

const boardMakingColumns = ref([]);
const boardMakingTalbeData = ref([]);

const sourceAccessorySpecs = ref([])

// 验证规则
const rule = reactive({});

const elFormRef = ref();

// 储存已有的颜色数据map
const colorMap = ref({});

// 客户确认大办单
const confirmOrderVisible = ref(false)
const confirmOrderForm = ref({ verifyTime: null })
const confirmOrderFormRef = ref()
const confirmOrderFormRules = ref({
    verifyTime: [
        { required: true, message: '请选择确认时间', trigger: 'blur' }
    ]
})

// 按钮权限
const printViewBtn = ref(false)
const printBtn = ref(false)
const saveBtn = ref(false)
const editBtn = ref(false)
const stopBtn = ref(false)
const cancelBtn = ref(false)
const recoverBtn = ref(false)
const completeBtn = ref(false)
const checkSuccessBtn = ref(false)
const equipmentPrintBtn = ref(false)
const submitHandleBtn = ref(false)
const submitHandleBtn1 = ref(false)
const agreeUpdateBtn = ref(false)
const refuseUpdateBtn = ref(false)
const exportDocumentBtn = ref(false)
const sapBtn = ref(false)
const rebackBtn = ref(false)
const customerSubmitBtn = ref(false)
const updateOrderToBtn = ref(false)
const leiyinBtn = ref(false)

const isViewOp = ref(false)
const editBDQXdialog = ref(false)
const oldeditBDQXData = ref()
const sapParam = ref({
    steps: '',
    factoryCode: '',
    stepList: [
        { label: '1、成品主档', value: 'step1' },
        { label: '2、颜色特性', value: 'step2' },
        { label: '3、尺码特性', value: 'step3' },
        { label: '4、分类', value: 'step4' },
        { label: '5、相关联', value: 'step5' },
        { label: '6、变式', value: 'step6' },
        { label: '7、后复色成品主档', value: 'step7' }
    ],
})

// 返回按钮
const back = () => {
    router.go(-1);
};

watchEffect(() => {
    //   基本资料 columns
    const newDetailFormColumns = [
        {
            label: "大办单编号",
            prop: "largeScaleNum",
        },
        {
            label: "客户编号",
            prop: "cumstomerNum",
        },
        {
            label: "片弧弯",
            prop: "sheetArcBend",
        },
        {
            label: "For specasavers",
            prop: "isForSpecasavers",
            slot: "isForSpecasavers",
        },
        {
            label: il8n("styleNum.label"),
            prop: "styleNum",
        },
        {
            label: il8n("customerStyleNum.label"),
            prop: "customerStyleNum",
        },
        {
            label: "本厂架倾角度",
            prop: "localTiltAngle",
        },
        {
            label: "完成时间",
            prop: "finishTime",
            needformatter:true,
            formatter: (finishTime) => formatDate(finishTime)
        },
        {
            label: "本厂款号",
            prop: "localStyleNum",
        },
        {
            label: il8n("customerBrand.label"),
            prop: "customerBrand",
        },
        {
            label: "客户架倾角度",
            prop: "customerTiltAngle",
        },
        {
            label: "入仓时间",
            prop: "warehousingTime",

            needformatter:true,
            formatter: (warehousingTime) => formatDate(warehousingTime)
        },
        {
            label: "SBU",
            prop: "sbuNum",
        },
        {
            label: il8n("series.label"),
            prop: "series",
        },
        {
            label: "眼型编号",
            prop: "glassType",
        },
        {
            label: "收货付数",
            prop: "warehousingAmount",
        },
        {
            label: "吉架要求完成",
            prop: "jijiaDemandDate",
            slot: "jijiaDemandDate",
            needformatter:true,
        },
        {
            label: "办单类型",
            prop: "orderProcessType",
            slot: "orderProcessType",
        },
        {
            label: "脾型编号",
            prop: "spleenTypeModel",
        },
        {
            label: il8n("createdAt.label"),
            prop: "CreatedAt",
            formatter: (date) => formatDate(date),
            needformatter:true,
        },
        {
            label: il8n("customerDemandDate.label"),
            prop: "customerDemandDate",
            slot: "customerDemandDate",
            needformatter:true,
        },
        // {
        //     label: "办单付数汇总",
        //     prop: "orderAmountSum",
        //     formatter: (sum) => sum || 0,
        // },
        {
            label: "参考首办单",
            prop: "referFirstOrderProcess",
        },
        {
            label: "创建人",
            prop: "createUser",
            solt: "createUser",
            // formatter: (createdUser) => {
            //     return createdUser?.nickName || ''
            // }
        },
        {
            label: "PI要求完成日期",
            prop: "piDemandDate",
            slot: "piDemandDate",
            needformatter:true,
        },
        {
            label: "附办数量",
            prop: "orderAmount",
            slot: "orderAmount",
        },
        {
            label: "首办回单",
            prop: "firstOrderReceipt",
            slot: "firstOrderReceipt",
        },
        {
            label: il8n("updatedAt.label"),
            needformatter:true,
            prop: "UpdatedAt",
            formatter: (date) => formatDate(date),
        },
        {
            label: "PI单号",
            prop: "piOrderNum",
            slot: "piOrderNum",
        },
        // {
        //     label: "生产地点",
        //     prop: "transferOrder",
        //     slot: "transferOrder",
        // },
        {
            label: "首办单回单备注",
            prop: "firstOrderReceiptNote",
            slot: "firstOrderReceiptNote",
        },
        {
            label: il8n("updateUser.label"),
            prop: "updateUser",
            slot: "updateUser",
            // formatter: (updatedUser) => {
            //     return updatedUser?.nickName || ''
            // }
        },
        {
            label: "第一版本创建时间",
            prop: "FirstCreatedAt",
            slot: "FirstCreatedAt",
        },
        {
            label: "参与周期计算",
            prop: "isCycleCountIn",
            slot: "isCycleCountIn",
        },
        {
            label: "新款",
            prop: "isNewStyle",
            slot: "isNewStyle",
        },
        {
            label: "印资",
            prop: "requireLetterpressMaterial",
            slot: "requireLetterpressMaterial",
        },
        // {
        //     label: "硬模编号",
        //     prop: "hardMoldNum",
        // },
    ];
    detailFormColumns.value = newDetailFormColumns;
    //   尺码 columns
    const newSizeColumns = [
        {
            prop: "sizeNum",
            label: il8n("ptlm_size.label"),
            show: true,
            fixedWidth: 100,
            tableColumnProps: {
                fixed: 'left',
                sortable: false,
            },
        },
        // {
        //     prop: "ptlm_color",
        //     label: il8n("ptlm_color.label"),
        //     show: true, // 通过 show 来控制列的展示或隐藏
        //     tableColumnProps: {
        //         sortable: false,
        //     },
        //     slot: "color",
        // },
        {
            prop: "luckTilt",
            fixedWidth: 100,
            label: "吉架",
            show: true,
            tableColumnProps: {
                fixed: 'right',
                sortable: false,
            },
            slot: "luckTilt",
        },
        {
            prop: "amountTotal",
            label: il8n("ptlm_count.label"),
            fixedWidth: 100,
            show: true,
            tableColumnProps: {
                fixed: 'right',
                sortable: false,
                formatter: (row) => {
                    return getColorSum(row)
                },
            },
        },
        {
            prop: "drawingList",
            label: il8n("ptlm_drawing_list.label"),
            width: 200,
            show: true,
            tableColumnProps: {
                fixed: 'right',
                sortable: false,
            },
            slot: "drawingList",
        },
    ];
    sizeColumns.value = newSizeColumns;
    // 作色要求
    const newColorColumns = [
        {
            prop: "colorNum",
            label: il8n("colorNum.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "customerColorNum",
            label: il8n("customerColorNum.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "customerStyleNum",
            label: il8n("customerStyleNum.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "localStyleDesc",
            label: il8n("localStyleDesc.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "circleColorRequire",
            label: il8n("circleColorRequire.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "spleenColorRequire",
            label: il8n("spleenColorRequire.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "otherColorRequire",
            label: il8n("otherColorRequire.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
    ];
    colorColumns.value = newColorColumns;
    // 标志\图案工艺说明
    const newSignColumns = [
        {
            prop: "accessoryName",
            label: il8n("accessoryName.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "position",
            label: il8n("position.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "workmanship",
            label: il8n("workmanship.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "workmanshipColor",
            label: il8n("workmanshipColor.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "workmanshipType",
            label: il8n("workmanshipType.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        // {
        //     prop: "accessoryNum",
        //     label: il8n("accessoryNum.label"),
        //     show: true, // 通过 show 来控制列的展示或隐藏
        //     tableColumnProps: {
        //         sortable: false,
        //     },
        // },
        {
            prop: "signNum",
            label: il8n("signNum.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "size",
            label: il8n("size.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "color",
            label: il8n("color.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            tableColumnProps: {
                sortable: false,
            },
        },
    ];
    signColumns.value = newSignColumns;
    //  测试标准
    const newTestStandardColumns = [
        {
            prop: "testName",
            label: il8n("testName.label"),
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "isReport",
            label: il8n("isReport.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            tableColumnProps: {
                sortable: false,
                formatter: (row) => (row.isReport == "true" ? "是" : "否"),
            },
        },
    ];
    testStandardColumns.value = newTestStandardColumns;

    // 办房复期
    const newBoardMakingColumns = [
        {
            prop: "ID",
            label: "序号",
            show: true,
            tableColumnProps: {
                width: '60px',
                type: 'index'
            },
        },
        {
            prop: "deliveryDate",
            label: "复期日",
            show: true,
            tableColumnProps: {
                sortable: false,
                formatter: (row) => formatDate(row.deliveryDate),
            },
        },

        {
            prop: "detailDescription",
            label: "详细说明",
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "createUser",
            label: "创建人/时间",
            show: true,
            tableColumnProps: {
                sortable: false,
                formatter: (row) =>
                    row.createUser + " " + formatDate(row.CreatedAt),
            },
        },
        {
            prop: "status",
            label: "状态",
            show: true,
            slot: "status",
            tableColumnProps: {
                sortable: false,
            },
        },

        {
            prop: "auditUser",
            label: "审核人/时间",
            show: true,
            tableColumnProps: {
                sortable: false,
                formatter: (row) =>
                    row.auditUser + " " + formatDate(row.auditDate),
            },
        },
        {
            prop: "auditDescription",
            label: "审核说明",
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
    ];
    boardMakingColumns.value = newBoardMakingColumns;
    // 历史修改备注
    const newHistoryNoteColumns = [
        {
            prop: "ID",
            label: "序号",
            show: true,
            tableColumnProps: {
                width: '60px',
                type: 'index'
            },
        },
        {
            prop: "content",
            label: "更改内容",
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "reason",
            label: "更改原因",
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "detail",
            label: "详情说明",
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        },
        {
            prop: "CreatedAt",
            label: "创建时间",
            show: true,
            tableColumnProps: {
                sortable: false,
                formatter: (row) => formatDate(row.CreatedAt, 'yyyy-MM-dd hh:mm:ss'),
            },
        },
        {
            prop: "createUser",
            label: "创建人",
            show: true,
            tableColumnProps: {
                sortable: false,
            },
        }
    ];
    historyNoteColumns.value = newHistoryNoteColumns;
});

onMounted(async () => {
    // 获取词典
    const dt = await useDict(
        "contentCate",
        "reasonCate",
        "firstOrderDestST101",
        "firstOrderDestNoST101",
        "orderType",
        "firstOrderReceiptNote",
        "transferOrder",
        "productionDepartment"
    );
    contentCate.value = dt.contentCate;
    reasonCate.value = dt.reasonCate;
    dict.value = dt;
    getFindLargeOrderProcessingDetail(true);
    const {
        query: { isView },
    } = route;
    if (isView) isViewOp.value = isView == 1

});

const setSku = (sizeData1 = [], colorData1 = []) => {
    let sizeData = Array.from(new Set(sizeData1));
    let colorData = Array.from(new Set(colorData1));
    let list = sizeData.reduce((pre, cur, index) => {
        let ll = colorData.map((item) => {
            return cur + " " + item;
        });
        return pre.concat(ll);
    }, []);
    return list;
};

const historyNoteTableDatadialog = ref(false)
const historyNoteTableDatas = ref()
const showhistoryNoteTableData = (row) =>{
    console.log(111);
    
    console.log(row.cmp_diff);
    if(row.cmp_diff){
        historyNoteTableDatadialog.value = true
        
        historyNoteTableDatas.value =row.cmp_diff
        

    }

    
}

async function getFindLargeOrderProcessingDetail(first) {
    const {
        query: { id, version },
    } = route;
    const res = await findLargeScaleOrder({ largeScaleNum: id, version });
    if (res.code === 0) {
        const {
            data: {
                relargeScaleOrder,
                relargeScaleOrder: {
                    sizes = [],
                    colors = [],
                    accessorySpecs = [],
                    signs = [],
                    modifyLogs = [],
                    mold_house = [],
                    tests = []
                },
            },
        } = res;
        formData.value = relargeScaleOrder;
        formData.value.orderTo = relargeScaleOrder.orderTo || {}
        oldeditBDQXData.value =  deepClone2(relargeScaleOrder.orderTo) || {}
        formData.value.productionDepartment=formData.value.productionDepartment?formData.value.productionDepartment:'辦房制作部'
        getBtn(relargeScaleOrder.status)
        sizeTableData.value = sizes.map((m) => {
            let name = m.drawingList.split("/")[m.drawingList.split("/").length - 1];
            if(!m.drawingName){
                m.drawingName = name
            }
            if (!m.colorNum) m.colorNum = {};
            return m;
        });
        if (first) {
            const col = colors.map(item => {
                return {
                    prop: item.colorNum,
                    label: item.colorNum,
                    show: true,
                    fixedWidth: 80,
                    tableColumnProps: {
                        sortable: false,
                    },
                    slot: 'color'
                }
            })
            if (col.length > 0) {
                sizeColumns.value.splice(1, 0, ...col);
            }
        }
        colorMap.value = {};
        let skuList = [];
        sizes?.map(m => {
            if (m.colorNum) {
                Object.keys(m.colorNum).forEach(key=>{
                    colorMap.value[key] = m.colorNum[key]?m.colorNum[key]:colorMap.value[key]
                    if(m.colorNum[key] && m.colorNum[key]>0){
                        skuList.push(m.sizeNum + " " + key)
                    }
                })
            }
        })
        
        colorTableData.value = colors.filter(item => colorMap.value[item.colorNum] && colorMap.value[item.colorNum] !== '0');;
        sourceAccessorySpecs.value = deepClone2(accessorySpecs);
        if (accessorySpecs){
            partTableData.value = initAccessorySpecs(accessorySpecs || [], colorTableData.value, sizeTableData.value);
        }
        testStandardDocumentListData.value = tests;
        signTableData.value = signs?.filter(item=>{
            let itemSize = item.size?item.size.split(',') : [];
            let itemColor = item.color?item.color.split(',') : [];
            let itemSkuList = setSku(itemSize,itemColor)
            let flag = itemSkuList.some(sku=>{
                return skuList.includes(sku)
            })
            return flag
        });
        historyNoteTableData.value = modifyLogs; 
        boardMakingTalbeData.value = mold_house;
        // 获取设计图列表
        // ddmsSpecDrawingListList(relargeScaleOrder.styleNum);
        // 获取规格参数
        getGuige(relargeScaleOrder.styleNum)
        // 状态不是草稿且版本不是1的时候请求版本对比
        if (relargeScaleOrder.version > 1 && first) {
            getAccessoryData()
        }
    }
}
function getGuige(params) {
    findProductSpec({ styleNum: params }).then((res) => {
        if (res.code == 0) {
            formData.value.productStyleNote = res.data.reproductSpec.styleNote
        }
    });
}
async function ddmsSpecDrawingListList(styleNum) {
    const res = await getDdmsSpecDrawingListList({ styleNum });
    if (res.code === 0) {
        const { list = [] } = res.data;
        ddmsSpecDrawingListListData.value = list;
    }
}

// async function testStandardDocumentList(customerNum) {
//     const res = await getTestStandardDocumentList({ customerNum });
//     if (res.code === 0) {
//         const { list = [] } = res.data;
//         testStandardDocumentListData.value = list;
//     }
// }

function submitupdateForm(controls) {
    if(formData.value.status == '制辦管理處理中'){
        ElMessage({
            type: "error",
            offset: "25",
            message: "辦房管理處理中不允許改單，請與辦房聯繫退單後修改",
        });
        return
    }
    addNoteForm.value = {};
    // if (!compareNums(sizeTableData.value, formData.value.firstOrderDest)) return
    // if (formData.value.status === '草稿') {
        emitter.emit("closeThisPage", {
            path: "/layout/plmLargeOrderProcessingAdd",
            query: { id: formData.value.largeScaleNum,dataTime:new Date().getTime() }
        });
        // return
    // }
    // changeAddNoteDialogFormVisible(true);
    // if (formData.value.submitNums > 0) {
    //     // 需要填写原因
    //     changeAddNoteDialogFormVisible(true);
    // }
    // else {
    //     confirmNoReasonForm(() => { 
    //         updateStatus(controls)
    //     })
    // }
}

// 获取办房复期
async function getLargeScaleOrderMoldHouseList(largeScaleNum) {
    if (formData.value.largeScaleNum) {
        const res = await largeScaleOrderMoldHouseList({ largeScaleNum });
        if (res.code === 0) {
            boardMakingTalbeData.value = res.data.list;
        }
    }
}

// 获取颜色的总和
function getColorSum(row) {
    let num = 0
    for (const key in row.colorNum) {
        num += Number(row.colorNum[key] || 0)
    }
    num += (row.luckTilt || 0)
    return num;
}

function confirmEditForm(controls) {
    addNoteFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log("==============", addNoteForm);
            const note = deepClone2(addNoteForm.value);
            note.content = Array.isArray(note.content)
                ? note.content.join("\n")
                : note.content;
            note.reason = Array.isArray(note.reason)
                ? note.reason.join("\n")
                : note.reason;
            const res = await updateLargeScaleOrderStatus({
                controls,
                ID: String(formData.value.ID),
                largeScaleOrderModifyNote: [note]
            })

            if (res.code === 0) {
                // // 打开弹窗
                // changeAddNoteDialogFormVisible(false);
                // const resd = await findLargeScaleOrder({ largeScaleNum: formData.value.largeScaleNum });
                // const { data: { relargeScaleOrder: { status } } } = resd
                // if (status === '暫停確認中' ||
                //     status === '終止確認中' ||
                //     status === '改單審批中'
                // ) {
                //     // emitter.emit("reload");
                //     return
                // }
                if (formData.value.status == '制辦管理處理中' || formData.value.status == '草稿' || formData.value.status == '制辦中心處理中') {
                    emitter.emit("closeThisPage", {
                        path: "/layout/plmLargeOrderProcessingAdd",
                        query: { id: formData.value.largeScaleNum }
                    });
                } else {
                    emitter.emit("closeThisPage", {
                        path: "/layout/plmLargeOrderProcessing",
                    });
                    addNoteForm.value = {};
                }
                // router.push({
                //     path: "/layout/plmLargeOrderProcessingAdd",
                //         query: { id: formData.value.ID }
                //     });
                // ElMessage({
                //     type: "success",
                //     message: "修改成功",
                // });
                // updateStatus('提交')

            }

            // historyNoteTableData.value.push(note);
            // const relargeScaleOrder = {
            //     ...formData.value,
            // };

            // let orderAmountSum = 0
            // relargeScaleOrder.sizes = sizeTableData.value;
            // relargeScaleOrder.sizes.forEach(item=>{
            //     item.amountTotal = getColorSum(item)
            //     orderAmountSum += Number(item.amountTotal)
            // })
            // relargeScaleOrder.colors = colorTableData.value;
            // relargeScaleOrder.accessorySpecs = sourceAccessorySpecs.value;
            // relargeScaleOrder.signs = signTableData.value;
            // relargeScaleOrder.modifyNotes = historyNoteTableData.value;
            // relargeScaleOrder.tests = testStandardDocumentListData.value;
            // relargeScaleOrder.orderAmount = String(
            //     relargeScaleOrder.orderAmount
            // );
            // relargeScaleOrder.orderAmountSum = orderAmountSum;
            // const params = { ...relargeScaleOrder };
            // console.log("params=============", params);
            // const res = await updateLargeScaleOrder(params);
            // if (res.code === 0) {
            //     addNoteForm.value = {};
            //     ElMessage({
            //         type: "success",
            //         message: "修改成功",
            //     });
            //     updateStatus('提交')       
            //     changeAddNoteDialogFormVisible(false);

            // }
        }
    });
}

async function confirmNoReasonForm(callback) {
    const relargeScaleOrder = {
    ...formData.value,
  };
  let orderAmountSum = 0;
  relargeScaleOrder.sizes = tableData.value;
  relargeScaleOrder.sizes.forEach((item) => {
    item.amountTotal = getCount(item);
    orderAmountSum += Number(item.amountTotal);
    let ll = item.ddmsDrawingLists?.filter(
        (val) => val.fileUrl == item.drawingList
    );
    if (ll && ll.length > 0) {
        item["drawingName"] = ll[0].drawingName;
        item["ddmsNum"] = ll[0].ddmsNum || '';
        item["ddmsNumVersion"] = ll[0].version || '';
    }else{
      item["drawingName"] = '';
      item["ddmsNum"] = '';
      item["ddmsNumVersion"] = '';
    }
  });
  // relargeScaleOrder.colors = colorTableData.value;
  // relargeScaleOrder.accessorySpecs = sourceAccessorySpecs.value;
  // relargeScaleOrder.signs = signTableData.value;
  // relargeScaleOrder.modifyNotes = historyNoteTableData.value;
  // relargeScaleOrder.tests = testStandardDocumentListData.value;
  relargeScaleOrder.orderAmount = String(relargeScaleOrder.orderAmount);
  relargeScaleOrder.orderAmountSum = orderAmountSum;
  const params = { ...relargeScaleOrder };
  console.log("params=============", params);
  const res = await updateLargeScaleOrder(params);
  if (res.code === 0) {
    // addNoteForm.value = {};
    ElMessage({
      type: "success",
      message: "修改成功",
    });
    const {
      query: { id },
    } = route;
    emitter.emit("closeThisPage", {
      path: "/layout/plmLargeOrderProcessingEdit",
      query: { id: id, subTitle: id },
    });
  }
}

function addBoardMaking() {
    boardMakingForm.value = {};
    changeBoardMakingVisible(true);
}

function addBoardMakingSubmit() {
    boardMakingFormRef.value.validate(async (valid) => {
        if (valid) {
            const params = {
                ...boardMakingForm.value,
                largeScaleNum: formData.value.largeScaleNum,
            };
            console.log("params==============", params);
            const res = await createLargeScaleOrderMoldHouse(params);
            if (res.code === 0) {
                boardMakingForm.value = {};
                ElMessage({
                    type: "success",
                    message: "添加成功",
                });
                changeBoardMakingVisible(false);
                getLargeScaleOrderMoldHouseList(params.largeScaleNum);
            }
        }
    });
}

function auditBoardMaking(row) {
    auditBoardMakingForm.value = {
        ID: row.ID,
    };
    changeAuditBoardMakingVisible(true);
}

function auditBoardMakingSubmit() {
    auditBoardMakingFormRef.value.validate(async (valid) => {
        if (valid) {
            const params = {
                ...auditBoardMakingForm.value,
                largeScaleNum: formData.value.largeScaleNum,
            };
            console.log("audit params========================", params);
            const res = await updateLargeScaleOrderMoldHouse(params);
            if (res.code === 0) {
                auditBoardMakingForm.value = {};
                ElMessage({
                    type: "success",
                    message: "审核成功",
                });
                changeAuditBoardMakingVisible(false);
                getLargeScaleOrderMoldHouseList(params.largeScaleNum);
            }
        }
    });
}

async function updateStatus(controls, confirm) {
    if (confirm) {
        if (controls === '提交') {
            if (!formData.value.localStyleNum) {
                ElMessage({
                    type: "error",
                    message: "大办单本厂款号为空！",
                });
                return false
            }
        }
        ElMessageBox.confirm(`确定要${controls}吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            confirmUpdateStatus(controls)
        })
    }
    else {
        confirmUpdateStatus(controls)
    }
}

// confirmUpdateStatus
async function confirmUpdateStatus(controls) {
    const res = await updateLargeScaleOrderStatus({
        controls,
        ID: String(formData.value.ID),
    })
    if (res.code === 0) {
        // if (controls === '同意') {
        //     router.push({
        //     path: "/layout/plmLargeOrderProcessing"
        //     });
        //     return
        // }
        getFindLargeOrderProcessingDetail()
        ElMessage({
            type: "success",
            message: "大办单修改成功",
        });
        emitter.emit("closeThisPage", {
            path: "/layout/plmLargeOrderProcessing",
            query: {}
        });
    }
}

// async function handleSubmit(controls) { 
//     if (!compareNums(sizeTableData.value, formData.value.firstOrderDest)) return
//     const relargeScaleOrder = {
//         ...formData.value,
//     };
//     let orderAmountSum = 0;
//     relargeScaleOrder.sizes = sizeTableData.value;
//     relargeScaleOrder.sizes.forEach(item=>{
//         item.amountTotal = getColorSum(item)
//         orderAmountSum += Number(item.amountTotal)
//     })
//     relargeScaleOrder.colors = colorTableData.value;
//     relargeScaleOrder.accessorySpecs = sourceAccessorySpecs.value;
//     relargeScaleOrder.signs = signTableData.value;
//     relargeScaleOrder.modifyNotes = historyNoteTableData.value;
//     relargeScaleOrder.tests = testStandardDocumentListData.value;
//     relargeScaleOrder.orderAmount = String(
//         relargeScaleOrder.orderAmount
//     );
//     relargeScaleOrder.orderAmountSum = orderAmountSum;
//     const params = { ...relargeScaleOrder };
//     console.log("params=============", params);
//     const res = await updateLargeScaleOrder(params);
//     if (res.code === 0) {
//         updateStatus(controls)
//     }

// }

function initBtn() {
    printViewBtn.value = false
    printBtn.value = false
    saveBtn.value = false
    editBtn.value = false
    stopBtn.value = false
    cancelBtn.value = false
    recoverBtn.value = false
    completeBtn.value = false
    checkSuccessBtn.value = false
    equipmentPrintBtn.value = false
    submitHandleBtn.value = false
    submitHandleBtn1.value = false
    agreeUpdateBtn.value = false
    refuseUpdateBtn.value = false
    exportDocumentBtn.value = false
    sapBtn.value = false
    rebackBtn.value = false
    customerSubmitBtn.value = false
    updateOrderToBtn.value = false
    leiyinBtn.value = false
}

async function getBtn(status) {
    initBtn()
    switch (status) {
        case "草稿":
            editBtn.value = true
            submitHandleBtn1.value = true
            break
        case "暫停確認中":
        case "終止確認中":
        case "改單審批中":
            agreeUpdateBtn.value = true
            refuseUpdateBtn.value = true
            break;
        case "暫停":
            recoverBtn.value = true
            break;
        case "制辦中心處理中":
            leiyinBtn.value = true
        case "制辦管理處理中":
            editBtn.value = true
            stopBtn.value = true
            cancelBtn.value = true
            printViewBtn.value = true
            printBtn.value = true
            leiyinBtn.value = true
            completeBtn.value = status === '制辦中心處理中' && formData.value.printStatus === '已打印'
            submitHandleBtn.value = status === '制辦管理處理中' && formData.value.printStatus === '已打印' ? true : false

            exportDocumentBtn.value = true
            sapBtn.value = true
            rebackBtn.value = status === "制辦管理處理中"
            break;
        case "大辦單完成":
            printViewBtn.value = true
            customerSubmitBtn.value = true
            break;
    }
}

// 判断办单付数 和 办单去向总数数量对比
function compareNums(sizes = [], firstOrderDest = {}) {
    let firstOrderDestNums = 0
    for (let key in firstOrderDest) {
        if (firstOrderDest[key]) {
            firstOrderDestNums += Number(firstOrderDest[key])
        }

    }
    let sizeNums = 0
    sizes.map(sm => {
        if (sm.colorNum) {
            for (let key in sm.colorNum) {
                if (sm.colorNum[key]) {
                    sizeNums += Number(sm.colorNum[key])
                }
            }
        }
        if (sm.luckTilt) sizeNums += Number(sm.luckTilt)
    })
    if (firstOrderDestNums !== sizeNums) {
        ElMessage({
            type: "error",
            message: "办单去向总数只能等于办单付数总数",
        });
        return false
    }
    return true
}


function validNumber(data, type) {
    data[type] = data[type].replace(/[^0-9]/gi, '');
}
// 后端路径
const path1 = ref(import.meta.env.VITE_BASE_API + "/");
async function print(flag) {
    let params = { largeScaleNum: formData.value.largeScaleNum }
    if (flag) {
        params['isPreview'] = '1'
    }
    const res = await largeScaleOrderPrint(params)
    if (res.code === 0) {
        const fileUrl = path1.value + res.data.fileUrl;
        if (!fileUrl) return;
        // if (flag) {
        //     router.push({
        //         path: "/layout/print",
        //         query: { fileUrl: encodeURIComponent(fileUrl), flag: flag }
        //     });
        // } else {
            const link = document.createElement("a");
            link.href = fileUrl;
            const name = res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
            link.setAttribute("download", name);
            link.click();
            // emitter.emit("reload");
        // }
    }
}

async function largeScaleOrderExportMaterialListFun() {
    const res = await largeScaleOrderExportMaterialList({ ID: formData.value.ID })
    if (res.code === 0) {
        const path1 = ref(import.meta.env.VITE_BASE_API + "/");
        const fileUrl = path1.value + res.data.fileUrl;
        const link = document.createElement("a");
        link.href = fileUrl;
        let name =
            res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
        link.setAttribute("download", name);
        link.click();
    }
}

function getSumaryMethod(SummaryMethodProps) {
    const { columns, data } = SummaryMethodProps
    const sums = []

    columns.forEach((column, index) => {
        if (column.property === 'luckTilt') {
            sums[index] = '合计'
            return
        }
        const values = data.map((item) => Number(item[column.property]))

        if (column.property === 'amountTotal' && !values.every((value) => Number.isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                    return prev + curr
                } else {
                    return prev
                }
            }, 0)
        }
    })
    return sums
}

// 新增与上版本配件对比
const addAccessory = ref([]);
const deleteAccessory = ref([]);
function getAccessoryData(params) {
    const {
        query: { id },
    } = route;
    let dd = { largeScaleNum: id }
    if(route.query.version) {dd['version'] = route.query.version}
    versionComparison(dd).then(res => {
     
        
        if (res.code == 0) {
            addAccessory.value = []
            deleteAccessory.value = []
            if (res.data.Add) {
                res.data.Add.map((item) => {
                    let idx = addAccessory.value.findIndex((p) => {
                        return p == (item.componentNum || '') + (item.colorNum || '')
                    });
                    let p = (item.componentNum || '') + (item.colorNum || '')
                    if (idx == -1 && p) {
                        addAccessory.value.push(p);
                    }
                });
            }
            if (res.data.Decrease) {
                res.data.Decrease.map((item) => {
                    let idx = deleteAccessory.value.findIndex((p) => {
                        return p == (item.componentNum || '') + (item.colorNum || '')
                    });
                    let p = (item.componentNum || '') + (item.colorNum || '')
                    if (idx == -1 && p) {
                        deleteAccessory.value.push(p);
                    }
                });
            }
        }
    })
}

function confirmOrder() {
    confirmOrderVisible.value = true
}

function handleConfirmOrder() {
    confirmOrderFormRef.value?.validate(async (valid) => {
        if (valid) {
            const params = {
                ...confirmOrderForm.value,
                ID: String(formData.value.ID),
            }
            const res = await customerConfirmLargeScaleOrderTime(params)
            if (res.code === 0) {
                ElMessage({
                    type: "success",
                    message: "确认成功",
                });
                confirmOrderVisible.value = false
                // getFindFirstOrderProcessingDetail()

                emitter.emit("closeThisPage", {
                    path: "/layout/plmLargeOrderProcessing",
                    query: {}
                });
            }
        }
    })
}

function getParams() {

    let params = {
        ID: formData.value.ID,
        getParam: 1,
        steps: sapParam.value.steps,
        factoryCode: sapParam.value.factoryCode,
    }
    exportToSap2(params, '/largeScaleOrder/exportToSap')
        .then((res) => {
            // console.log(res);
            // 后端路径
            const path1 = import.meta.env.VITE_BASE_API + "/";
            const fileUrl = path1 + res.data.fileUrl;
            // const link = document.createElement("a");
            // link.href = fileUrl;
            // let name =
            //     res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
            // link.setAttribute("download", name);
            // link.click();
            const x = new XMLHttpRequest();
            x.open("GET", fileUrl, true);
            x.responseType = "blob";
            x.onload = (e) => {
                let { status, readyState } = x;
                if (status === 200 && readyState === 4) {
                    // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
                    const url = window.URL.createObjectURL(x.response);
                    const a = document.createElement("a");
                    a.href = url;
                    let name = res.data.fileUrl.split("/")[res.data.fileUrl.split("/").length - 1];
                    a.download = name;
                    a.click();
                } else {
                    if (status === 404) {
                        ElMessage({
                            type: "warning",
                            message: "文件不存在",
                        });
                    } else {
                        ElMessage({
                            type: "warning",
                            message: "下载出错",
                        });
                    }
                }
            };
            x.send();
        })
        .catch((err) => {
            console.log("err===>", err);
        });
}

const toSapRef = ref()
function toSapFun() {
    toSapRef.value.toSap()
}

// 下载
const downloadFile = (row) => {
    let params = {
        drawingName: row.drawingName,
        fileUrl: row.drawingList,
    };
    downloadFilePost(params).then((data) => {
        if (data.response && data.response.status == 404) {
            ElMessage({
                type: "warning",
                message: "文件不存在",
            });
            return;
        }
        let blob = new Blob([data.data], {});
        const fileName = row.drawingName;
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 下载完成移除元素
        window.URL.revokeObjectURL(url); // 释放掉blob对象
    });
    // let fileUrl;
    // if (
    //     row.drawingList.indexOf("http://") > -1 ||
    //     row.drawingList.indexOf("https://") > -1
    // ) {
    //     fileUrl = row.drawingList.replace(new RegExp("#", "g"), "");
    // } else {
    //     fileUrl =
    //         path1.value + row.drawingList.replace(new RegExp("#", "g"), "");
    // }
    // const x = new XMLHttpRequest();
    // x.open("GET", fileUrl, true);
    // x.responseType = "blob";
    // x.onload = (e) => {
    //     let { status, readyState } = x;
    //     if (status === 200 && readyState === 4) {
    //         // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
    //         const url = window.URL.createObjectURL(x.response);
    //         const a = document.createElement("a");
    //         a.href = url;
    //         let name = row.drawingList.split("/")[row.drawingList.split("/").length - 1];
    //         a.download = row.drawingName ? row.drawingName.replace(new RegExp("#", "g"), "") : name;
    //         a.click();
    //     } else {
    //       if (status === 404) {
    //           ElMessage({
    //               type: "warning",
    //               message: "文件不存在",
    //           });
    //       } else {
    //           ElMessage({
    //               type: "warning",
    //               message: "下载出错",
    //           });
    //       }
    //   }
    // };
    // x.send();
};

function productionDepartmentChange(params) {
    updateProductionDepartment({ ID: formData.value.ID, productionDepartment: params }).then(res => {
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "修改制作部门成功",
            });
        }
    })
}

function editPrintStatus(params) {
  moldHousePrint({largeScaleNum: formData.value.largeScaleNum })
}

// 修改办单去向弹窗打开
function editBDQX(params) {
    editBDQXdialog.value = true
}

// 修改办单去向弹窗确定
function handleConfirmBDQX(params) {
    let otherNums = 0
    for (let key in formData.value.orderTo) {
        if (key !== '其他'&&key!=='otherReason') {
            otherNums += formData.value.orderTo[key]
        }
    }
    if(otherNums>formData.value.orderAmountSum) {
        ElMessage({
            type: "error",
            message: "办单去向总数只能等于办单付数总数",
            });
        return
    }


    let datas = {
        largeScaleNum:formData.value.largeScaleNum,
        orderTo:formData.value.orderTo
    }
    updateLargeScaleOrderTo(datas).then(res=>{
        if(res.code==0) {
            editBDQXdialog.value = false
            ElMessage({
                type: "success",
                message: "修改办单去向成功",
            });
        }
    })
}

// 计算去向的其他
function BDQXchange(params) {
    let otherNums = 0
    for (let key in formData.value.orderTo) {
        if (key !== '其他'&&key!=='otherReason') {
            otherNums += formData.value.orderTo[key]
        }
    }
    formData.value.orderTo['其他'] =formData.value.orderAmountSum - otherNums || 0
    if(formData.value.orderTo['其他']<1) {
        formData.value.orderTo['otherReason'] = ''
    }
}


// 打印预览----------------------------------------------------------
function getPrintStyle() {
    return `@page{marign:0;padding:0;}
   .one-box {
	display: flex;
	justify-content: space-between;
	margin-top: 10px;
	padding-bottom: 6px;
	border-bottom: 2px solid rgb(240, 240, 240);
}
.one-box > div {
	font-size: 18px !important;
	text-align: left;
	width: 33.33%;
}
.one-box > div:last-child {
	margin-top: 10px;
	text-align: right;
}
.one-box .ftsz10px {
	font-size: 6px !important;
}
.content-box {
	margin-top: 4px;
}
.content-box .title {
	margin-bottom: 4px;
	font-size: 8px;
	font-weight: bold;
}
.content-box .content {
	border-top: 2px solid rgb(240, 240, 240);
	border-bottom: 2px solid rgb(240, 240, 240);
	padding: 10px 0 0px;
}
.content-box .content .descriptions {
	display: flex;
	flex-wrap: wrap;
	font-size: 6px !important;
}
.content-box .content .descriptions .descriptionsItem {
	width: 25%;
	margin-bottom: 2px;
	font-size: 6px !important;
}
.content-box .content .descriptions .addLine {
	margin-bottom: 2px;
	width: 100%;
	font-size: 6px !important;
}
.content-box .content .myTable-head {
	display: flex;
	justify-content: space-around;
	text-align: left;
	padding-bottom: 2px;
	border-bottom: 3px solid rgb(240, 240, 240);
}
.content-box .content .myTable-head > div {
	flex: 4;
	font-size: 6px !important;
}
.content-box .content .myTable-head > div:first-child {
	flex: 2;
}
.content-box .content .myTable-head > div:nth-child(3) {
	flex: 2;
}
.content-box .content .myTable-content {
	display: flex;
	justify-content: space-around;
	text-align: left;
	margin-top: 1px;
	padding-bottom: 1px;
	border-bottom: 1px solid rgb(240, 240, 240);
}
.content-box .content .myTable-content > div {
	flex: 4;
	font-size: 6px !important;
	padding: 0 2px;
}
.content-box .content .myTable-content > div:first-child {
	flex: 2;
}
.content-box .content .myTable-content > div:nth-child(2) {
	flex: 2;
}
.content-box .content .myTable-content > div:nth-child(3) {
	flex: 2;
}
.content-box .content .myTable-content:last-child {
	border-bottom: 0px solid rgb(240, 240, 240);
}
.table1 .myTable-head > div,
.table1 .myTable-content > div {
	flex: 10 !important;
}
.table1 .myTable-head > div:first-child,
.table1 .myTable-content > div:first-child {
	flex: 2 !important;
}
.table1 .myTable-head > div:nth-child(2),
.table1 .myTable-content > div:nth-child(2) {
	flex: 9 !important;
}
.table1 .myTable-head > div:nth-child(3),
.table1 .myTable-content > div:nth-child(3) {
	flex: 12 !important;
}
.table2 .myTable-head > div,
.table2 .myTable-content > div {
	flex: 10 !important;
	word-break: break-all;
}
.table2 .myTable-head > div:first-child,
.table2 .myTable-content > div:first-child {
	flex: 10 !important;
}
.table2 .myTable-head > div:nth-child(2),
.table2 .myTable-content > div:nth-child(2) {
	flex: 4 !important;
}
.table2 .myTable-head > div:nth-child(5),
.table2 .myTable-content > div:nth-child(5) {
	flex: 4 !important;
}
.table2 .myTable-head > div:nth-child(6),
.table2 .myTable-content > div:nth-child(6) {
	flex: 4 !important;
}
.table2 .myTable-head > div:nth-child(7),
.table2 .myTable-content > div:nth-child(7) {
	flex: 4 !important;
}
.table3 .myTable-head > div,
.table3 .myTable-content > div {
	flex: 10 !important;
}
.table3 .myTable-head > div:first-child,
.table3 .myTable-content > div:first-child {
	flex: 5 !important;
}
.table3 .myTable-head > div:nth-child(2),
.table3 .myTable-content > div:nth-child(2) {
	flex: 5 !important;
}
.table3 .myTable-head > div:nth-child(3),
.table3 .myTable-content > div:nth-child(3) {
	flex: 5 !important;
}
.table3 .myTable-head > div:nth-child(4),
.table3 .myTable-content > div:nth-child(4) {
	flex: 15 !important;
}
.table3 .myTable-head > div:nth-child(5),
.table3 .myTable-content > div:nth-child(5) {
	flex: 3 !important;
}
.table3 .myTable-head > div:nth-child(6),
.table3 .myTable-content > div:nth-child(6) {
	flex: 6 !important;
}
.table3 .myTable-head > div:nth-child(7),
.table3 .myTable-content > div:nth-child(7) {
	flex: 10 !important;
}
.table3 .myTable-head > div:nth-child(8),
.table3 .myTable-content > div:nth-child(8) {
	flex: 5 !important;
}
.table4 .myTable-head > div,
.table4 .myTable-content > div {
	flex: 10 !important;
}
.table4 .myTable-head > div:first-child,
.table4 .myTable-content > div:first-child {
	flex: 8 !important;
}
.table4 .myTable-head > div:nth-child(2),
.table4 .myTable-content > div:nth-child(2) {
	flex: 8 !important;
}
.table4 .myTable-head > div:nth-child(3),
.table4 .myTable-content > div:nth-child(3) {
	flex: 14 !important;
}
   `;
}
const printPartTableData = ref([])
// 给树中增加层级字段并变成数组
function addLevelField(tree, selfLevel = 1) {
    for (let node of tree) {
        if (node) {
            node.selfLevel = selfLevel; // 在节点上添加selfLevel字段
            printPartTableData.value.push(node)
            if (node.children && node.children.length > 0) {
                addLevelField(node.children, selfLevel + 1); // 递归处理子节点
            }
        }
    }
    return tree; // 返回处理后的树
}

const previewDialogShow = ref(false);
function preview(params) {
    console.log('检查是不是有数据错误的问题:', partTableData.value);
    printPartTableData.value = []
    addLevelField(partTableData.value)
    previewDialogShow.value = true;
}

function closePreview(params) {
    previewDialogShow.value = false;
}

</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.title-box {
    display: flex;
    align-items: center;
    position: relative;
    .title {
        font-size: 20px;
        font-weight: 600;
        margin-right: 8px;
    }
}

.mt-20px {
    margin-top: 20px;
}

.b-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
    width: 9%;
}

:deep(.el-descriptions__content) {
    width: 16%;
    word-break: break-all;
    white-space: pre-wrap;
}

.large-order-form {
    :deep(.el-form-item__label) {
        width: 96px;
    }
}

.list-header {
    margin-top: 20px;
}

:deep(.el-table__expand-icon) {
    // display: none !important;
    opacity: 0;
}

.version-PK {
    :deep(.delete-acc) {
        background: #fd9595 !important;
        color: #000 !important;
    }

    :deep(.el-descriptions__label) {
        width: 2%;
    }
}
:deep(.table-style-1){
    .el-table__cell{
        vertical-align: top !important;
    }
}



// 预览
.one-box {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  > div {
    font-size: 18px !important;
    text-align: left;
    width: 33.33%;
    &:last-child {
      margin-top: 10px;
      text-align: right;
    }
  }

  padding-bottom: 6px;
  border-bottom: 2px solid rgb(240, 240, 240);

  .ftsz10px {
    font-size: 8px !important;
  }
}

.content-box {
  margin-top: 4px;
  .title {
    margin-bottom: 4px;
    font-size: 8px;
    font-weight: bold;
  }

  .content {
    border-top: 2px solid rgb(240, 240, 240);
    border-bottom: 2px solid rgb(240, 240, 240);
    padding: 10px 0 0px;

    .descriptions {
        display: flex;
        flex-wrap: wrap;
        font-size: 8px !important;
        .descriptionsItem {
            width: 25%;
            margin-bottom: 2px;
            font-size: 8px !important;
        }
        .addLine {
            margin-bottom: 2px;
            width: 100%;
            font-size: 8px !important;
        }
    }
    .myTable-head {
      display: flex;
      justify-content: space-around;
      text-align: left;
      padding-bottom: 2px;
      > div {
        flex: 4;
        font-size: 8px !important;
        &:first-child {
          flex: 2;
        }
        &:nth-child(3) {
          flex: 2;
        }
      }

      border-bottom: 3px solid rgb(240, 240, 240);
    }
    .myTable-content {
      display: flex;
      justify-content: space-around;
      text-align: left;
      margin-top: 1px;
      padding-bottom: 1px;
      > div {
        flex: 4;
        font-size: 8px !important;
        padding: 0 2px;
        &:first-child {
          flex: 2;
        }
        &:nth-child(2) {
          flex: 2;
        }
        &:nth-child(3) {
          flex: 2;
        }
      }

      border-bottom: 1px solid rgb(240, 240, 240);
      &:last-child {
        border-bottom: 0px solid rgb(240, 240, 240);
      }
    }
  }
}

.table1 {
  .myTable-head,
  .myTable-content {
    > div {
      flex: 10 !important;
      &:first-child {
        flex: 2 !important;
      }
      &:nth-child(2) {
        flex: 9 !important;
      }
      &:nth-child(3) {
        flex: 12 !important;
      }
    }
  }
}

.table2 {
  .myTable-head,
  .myTable-content {
    > div {
      flex: 10 !important;
      word-break: break-all;

      &:first-child {
        flex: 10 !important;
      }
      &:nth-child(2) {
        flex: 4 !important;
      }

      &:nth-child(5) {
        flex: 4 !important;
      }
      &:nth-child(6) {
        flex: 4 !important;
      }
      &:nth-child(7) {
        flex: 4 !important;
      }
    }
  }
}

.table3 {
  .myTable-head,
  .myTable-content {
    > div {
      flex:10 !important;
      &:first-child {
        flex: 5 !important;
      }
      &:nth-child(2) {
        flex: 5 !important;
      }
      &:nth-child(3) {
        flex: 5 !important;
      }
      &:nth-child(4) {
        flex: 15 !important;
      }
      &:nth-child(5) {
        flex: 3 !important;
      }
      &:nth-child(6) {
        flex:6 !important;
      }
      &:nth-child(7) {
        flex: 10 !important;
      }
      &:nth-child(8) {
        flex: 5 !important;
      }
    }
  }
}

.table4 {
  .myTable-head,
  .myTable-content {
    > div {
      flex: 10 !important;
      &:first-child {
        flex: 8 !important;
      }
      &:nth-child(2) {
        flex: 8 !important;
      }
      &:nth-child(3) {
        flex: 14 !important;
      }
    }
  }
}

::v-deep .large-order-form[data-v-7e6c9f6f] .el-form-item__label {
    width: 96px;
    color: black;
}
::v-deep .el-input__inner::placeholder{
  color:black;-webkit-text-fill-color: black;
  
}
::v-deep .el-input.is-disabled .el-input__inner {
    
    -webkit-text-fill-color: black;
    cursor: not-allowed;
}

::v-deep .el-select__wrapper.is-disabled .el-select__selected-item {
    color: black;
}

::v-deep .el-radio__input.is-disabled + span.el-radio__label {
    color: black;
    cursor: not-allowed;
}
::v-deep .el-textarea.is-disabled .el-textarea__inner {
    box-shadow: 0 0 0 1px var(--el-disabled-border-color) inset;
    background-color: var(--el-disabled-bg-color);
    color: black;
    cursor: not-allowed;
}

:deep(.el-textarea.is-disabled .el-textarea__inner){
    background-color: #fff;
  color: var(--el-text-color-primary);
}
:deep(.el-input.is-disabled .el-input__inner){
    background-color: #fff;
  color: var(--el-text-color-primary);
  -webkit-text-fill-color: var(--el-text-color-primary);
}
:deep(.el-select__wrapper.is-disabled){
    background-color: #fff;
  color: var(--el-text-color-primary);
  -webkit-text-fill-color: var(--el-text-color-primary);
}

</style>
